package io.renren.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import io.renren.modules.security.SecurityUser;
import io.renren.modules.security.UserDetail;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;


/**
 * 公共字段，自动填充值
 * @author lzy
 */
@Component
public class FieldMetaObjectHandler implements MetaObjectHandler {
    private final static String CREATE_DATE = "createDate";
    private final static String CREATOR = "creator";
    private final static String UPDATE_DATE = "updateDate";
    private final static String UPDATER = "updater";

    @Override
    public void insertFill(MetaObject metaObject) {
        UserDetail user = SecurityUser.getUser();
        long now = System.currentTimeMillis();

        //创建者
        this.setInsertFieldValByName(CREATOR, user.getId(), metaObject);
        //创建时间
        Long createDate = (Long)getFieldValByName(CREATE_DATE, metaObject);
        if(null == createDate || createDate == 0) {
            this.setInsertFieldValByName(CREATE_DATE, now, metaObject);
        }
        //更新者
        this.setInsertFieldValByName(UPDATER, user.getId(), metaObject);
        //更新时间
        Long updateDate = (Long)getFieldValByName(UPDATE_DATE, metaObject);
        if(null == updateDate || updateDate == 0) {
            this.setInsertFieldValByName(UPDATE_DATE, now, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        //更新者
        this.setUpdateFieldValByName(UPDATER, SecurityUser.getUser().getId(), metaObject);

        //更新时间
        Long updateDate = (Long)getFieldValByName(UPDATE_DATE, metaObject);
        if(null == updateDate || updateDate == 0) {
            this.setUpdateFieldValByName(UPDATE_DATE, System.currentTimeMillis(), metaObject);
        }
    }
}
